<?php include dirname(__FILE__).'/common/header.php'; ?>
	document.title = '图片拼图';
	Ext.navActive = 'canvas';
	Ext.menuUrl = list.baseUrl+'code_canvas';

	list.leftNav = ZM.defaultLeftNav;
	var attr = {};
	attr.code_id = <?php echo $attr['code_id'] ?>;
	attr.width = <?php echo $attr['width'] ?>;
	attr.height = <?php echo $attr['height'] ?>;

	list.grid = new Ext.Container({
		layout:'border',
		items:[{
			xtype: 'panel',
			region: 'center',
			autoScroll: true,
			title: '拼图区域',
			bodyStyle:'background-color:#ccc;',
			tbar:[{
				text: '保存',
				cls: 'btn-show',
				handler: function() {
					//attr.cvInstance.removeShape();
					var wh = attr.cvInstance.getWH();
					var params = {code_id:attr.code_id,width:wh[0],height:wh[1]};
					var pStr = 'sprite[DDD][XXX]';
					for(var i = 0,len = spriteGrid.store.getCount(); i < len ; i++) {
						var r = spriteGrid.store.getAt(i);
						params[pStr.substring(0).replace('DDD',i).replace('XXX','sprite_id')] = r.get('sprite_id');
						params[pStr.substring(0).replace('DDD',i).replace('XXX','sprite_x')] = r.get('sprite_x');
						params[pStr.substring(0).replace('DDD',i).replace('XXX','sprite_y')] = r.get('sprite_y');
						params[pStr.substring(0).replace('DDD',i).replace('XXX','sprite_status')] = r.get('sprite_status');
					}
					Ext.getBody().mask('数据保存中...','x-mask-loading');
					ZM.ajax({
						url: list.baseUrl + 'code_canvas/saveSprite',
						params: params,
						success:function(res){
							ZM.bo.msg('成功!',res.detail);
							Ext.getBody().unmask();
							spriteGrid.store.reload();
							enableUpload();
						},
						failure:function(res) {
							Ext.getBody().unmask();
							Ext.Msg.alert('失败!',res.detail);
						}
					});
				}
			},'-',{
				xtype:'tbtext',
				id:'tb_canvas_size',
				text: attr.width + ' x ' + attr.height
			},'-',{
				text: '调整画布大小',
				cls: 'btn-show',
				handler: function() {
					var wh = attr.cvInstance.getWH();
					var frm = new ZM.FormPanel({
						items:[{
							xtype:'intfield',
							fieldLabel:'宽',
							minValue: 0,
							value: wh[0]
						},{
							xtype:'intfield',
							fieldLabel:'高',
							minValue: 0,
							value: wh[1]
						}],
						buttons:[{
							title:'调整画布大小',
							text:'提交',
							handler:function() {
								var w = frm.get(0).getValue()
									h = frm.get(1).getValue();
								attr.cvInstance.setWH(w,h);
								Ext.getCmp('tb_canvas_size').setText(w+' x '+h);
								list.grid.get(0).doLayout();
							}
						}]
					});
					var win = new ZM.PopUp({
						type: 's',
						items:frm
					});
					win.show();
				}
			},'->',new Ext.form.FormPanel({
					url:list.baseUrl + 'code_canvas/addCodeSprite',
					fileUpload:true,
					id:'form_upload_sprite',
					success:function(res) {
						ZM.bo.msg('成功!',res.detail);
						spriteGrid.store.reload();
						if(attr.cvInstance) attr.cvInstance.draw();
					},
					border: false,
					layout: 'fit',
					items:[
						{xtype:'hidden',name:'code_id',value:attr.code_id},
						{
							xtype:'fileuploadfield',
							name:'code_sprite[]',
							buttonText:'上传',
							buttonOnly:true,
							hideLabel:true,
							id:'field_code_sprite',
							allowBlank:false,
							listeners:{
								'fileselected':function(f,v) {
									ZM.submitForm(Ext.getCmp('form_upload_sprite'));
								}
							}
						}
					]
				})],
			items: {
				xtype: 'box',
				autoEl: {
					tag: 'canvas',
					id: 'sprite_canvas',
					width: attr.width,
					height:attr.height,
					style:'background-color:#30D699;border:1px dotted #000'
				},
				listeners:{
					afterrender: function(p) {
						attr.cvInstance = new cvtools({
							el:p.el,
							aftershapeposchange: function(selShape) {
								var r = getRecordFromGridById(spriteGrid,'sprite_id',selShape.id);
								if(r != null) {
									r.set('sprite_x',selShape.x);
									r.set('sprite_y',selShape.y);
									disableUpload();
								}
							},
							afteraddshape: function(addedShape) {
								var r = getRecordFromGridById(spriteGrid,'sprite_id',addedShape.id);
								if(r != null) {
									r.set('sprite_status',1);
									disableUpload();
								}
							},
							afterremoveshape: function(removedShape) {
								var r = getRecordFromGridById(spriteGrid,'sprite_id',removedShape.id);
								if(r != null) {
									r.set('sprite_status',-1);
									disableUpload();
								}
							},
							afterselectshape: function(selectedShape) {
								var r = getRecordFromGridById(spriteGrid,'sprite_id',selectedShape.id);
								spriteGrid.getSelectionModel().selectRecords([r]);
								var rowIndex = spriteGrid.store.indexOf(r);
								//console.log(rowIndex);
								spriteGrid.getView().getRow(rowIndex).scrollIntoView();
							},
							afterResizeCanvas: function() {
								list.grid.get(0).doLayout();
							},
							inResizeCanvas: function() {
								var wh = attr.cvInstance.getWH();
								Ext.getCmp('tb_canvas_size').setText(wh[0]+' x '+wh[1]);
							}
						});
						var wh = attr.cvInstance.getWH();
						Ext.getCmp('tb_canvas_size').setText(wh[0]+' x '+wh[1]);
					}
				}
			}
		},{
			xtype: 'gridpanel',
			width: 520,
			split: true,
			collapsible:true,
			collapseMode: 'mini',
			title: '小图列表',
			region: 'east',
			url: list.baseUrl + 'code_canvas/getCodeSpriteList',
			id: 'grid_sprite',
			history: 'sprite_id',
			autoExpandColumn:'pos',
			onlyShow: true,
			bbar:null,
			columns:[
				{header:'ID',dataIndex:'sprite_id',hidden:true},
				{header:'小图名',dataIndex:'sprite_name',width:150,renderer:function(v,p,r){
					if(r.data.sprite_status!=1){
						return '<span style="color:orange">'+v+' '+r.json.width+'x'+r.json.height+'</span>'
					}
					return v+' '+r.json.width+'x'+r.json.height;
				}},
				{header:'position',id:'pos',dataIndex:'',renderer:function(v,p,r){
					var x=0,y=0;
					if(r.data.sprite_x!=0){
						x = '-'+r.data.sprite_x+'px';
					}
					if(r.data.sprite_y!=0){
						y = '-'+r.data.sprite_y+'px';
					}
					return 'background-position:<big>'+x+' '+y+'</big>';
				}},
				//{header:'状态',dataIndex:'sprite_status',width:40,renderer:ZM.status},
				{header:'地址',dataIndex:'sprite_url',hidden:true},
				{header:'x坐标',dataIndex:'sprite_x',hidden:true,width:60},
				{header:'y坐标',dataIndex:'sprite_y',hidden:true,width:60},
				{header:'操作',dataIndex:'sprite_status',width:120,renderer:function(val,m,r) {
					var str = '';
					if(val == 1) {
						str += '<a href="#" id="_'+r.id+'" title="fireRemove" >[移除]</a>';
					} else {
						str += '<a href="#" id="_'+r.id+'" title="fireAdd" >[添加]</a>';
						str += '<a href="#" id="_'+r.id+'" style="color:red" title="fireDelete" >[删除]</a>';
					}
					str += '<a href="'+r.json.sprite_url+'" target="_blank" >[查看]</a>'
					return str;
				}}
			]
		}]
	});
	var spriteGrid = Ext.getCmp('grid_sprite');
	spriteGrid.fireDelete = function(r) {
		var r = r.json;
		Ext.Msg.confirm('确认?','确定要删除['+r.sprite_name+']?',function(btn) {
			if(btn != 'no') {
				ZM.ajax({
					url: list.baseUrl + 'code_canvas/deleteSprite',
					params:{sprite_id:r.sprite_id},
					success:function(res){
						ZM.bo.msg('success!',res.detail);
						location.reload();
					}
				});
			}
		});
	}
	spriteGrid.fireAdd = function(r) {
		attr.cvInstance.addShape({id:r.get('sprite_id'),src:r.get('sprite_url'),x:r.get('sprite_x'),y:r.get('sprite_y')});
	}
	spriteGrid.fireRemove = function(r) {
		attr.cvInstance.removeShape(r.get('sprite_id'));
	}
	spriteGrid.fireDetail = function(r) {
		attr.cvInstance.selectShape(r.get('sprite_id'));
	}
	
	function getRecordFromGridById(grid,field,id){
		for(var i = 0,len = grid.store.getCount(); i < len ; i++) {
			var r = spriteGrid.store.getAt(i);
			if(r.get(field) == id) {
				return r;
			}
		}
		return null;
	}
	
	function enableUpload() {
		Ext.getCmp('field_code_sprite').enable();
	}
	function disableUpload() {
		Ext.getCmp('field_code_sprite').disable();
	}
	
	var viewport = new Ext.Viewport({
		layout: 'fit',
		items: list.grid
	});
	
	spriteGrid.store.baseParams = {code_id:attr.code_id};
	spriteGrid.store.on('load',function(store,records) {
		(function(){
			if(attr.cvInstance == undefined){
				var self = arguments.arguments.callee;
				setTimeout(function(){self()},50);
			} else {
				attr.cvInstance.shapes = [];
				attr.cvInstance.clear();
				for(var i = 0 ,len = records.length ; i < len; i++) {
					var r = records[i];
					if(r.get('sprite_status') == 1) {
						attr.cvInstance.shapes.push({id:r.get('sprite_id'),src:r.get('sprite_url')
								,x:parseInt(r.get('sprite_x')),y:parseInt(r.get('sprite_y'))});
					}
				}
				attr.cvInstance.init();
			}
		})();
	});
	spriteGrid.store.load();
		<?php $includeCanvas=true ?>
<?php include dirname(__FILE__).'/common/footer.php'; ?>